import React, { useState, useEffect } from 'react'
import { Table, Image, Tooltip, Tag, Switch, Button, Upload, message, Modal } from 'antd'
import { fetchItems, addItems, updateItem, delItem } from '@a/item'
import SearchBar from '@/components/SearchBar';
import { useNavigate } from 'react-router-dom';
import './style.scss'
import { read, utils, writeFileXLSX } from 'xlsx';
export default function ItemLists() {
  const [modal, contextHolder] = Modal.useModal();
  const navigate = useNavigate();
  const [items, setItems] = useState([]);
  const [total, setTotal] = useState(0);
  const getItems = (page = 1, pageSize = 10, Searchparams = { key: '', start: '', end: '' }) => {
    fetchItems({
      page,
      pageSize,
      ...Searchparams
    }).then(res => {
      if (res.data.code === 200) {
        setItems(res.data.data.lists);
        setTotal(res.data.data.total)
      }

    })
  }
  // 点击页码和切换一页多少条
  const paginationChange = (page: number, pageSize: number) => {
    getItems(page, pageSize)

  }
  // 点击搜索
  const onSearch = (searchParams: { key: string, start: string, end: string }) => {
    getItems(undefined, undefined, searchParams)
  }
  useEffect(() => {
    getItems()
  }, [])
  const columns = [
    {
      title: '商品名',
      dataIndex: 'itemName',
      key: 'itemName'
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      key: 'price'
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render(value: string) {
        return (
          <Tooltip title={value}>
            <div>
              {value.substr(0, 15)}...
            </div>
          </Tooltip>
        )
      },
      key: 'desc'
    },
    {
      title: '销量',
      dataIndex: 'sale',
      render(sale: number) {
        return (
          <Tag color={sale > 500 ? 'red' : 'green'}>
            <span>{sale}</span>
          </Tag>
        )
      },
      key: 'sale'
    },
    {
      title: '上下架',
      dataIndex: 'onSale',
      render(onsale: boolean, row: { id: number; }) {
        return (
          <Switch
            checkedChildren="上架"
            unCheckedChildren="下架"
            defaultChecked={
              onsale
            }
            onChange={
              () => {
                switchItemEnable(row.id, onsale)
              }
            }
          />
        )
      },
      key: 'onSale'
    },
    {
      title: '封面',
      dataIndex: 'thumb',
      render(thumb: string) {
        return <Image src={thumb} width={100} />
      },
      key: 'thumb'
    },
    {
      title: '上架时间',
      dataIndex: 'createAt',
      key: 'createAt'
    },
    {
      title: '操作',
      render(index: number, row: { id: any; }) {
        return (
          <>
            <Button onClick={
              () => {
                navigate(`/itemUpdate?cateId=${row.id}`)
              }
            }>编辑</Button>
            <Button onClick={
              () => {
                removeItem(row.id)
              }
            } danger>删除</Button>
          </>
        )
      },
      key: 'action'
    }
  ]
  // 行内修改商品上下架状态
  const switchItemEnable = (id: number, onsale: boolean) => {
    updateItem({
      id,
      onsale
    }).then(res => {
      if (res.data.code === 200){
        message.success(res.data.msg, 2, () => {
          getItems()
        })
      }
    })
  }
  // 点击上传 excel 批量添加商品
  const uploadXlsx = (file: any) => {
    // 将文件 读取成arrayBuffer格式
    const fd = new FileReader();
    fd.readAsArrayBuffer(file);
    fd.onload = () => {
      // fd.result
      const wb = read(fd.result);
      const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      const _data = data.map((el:any) => {
        return {
          itemName: el.商品名,
          price: el.价格,
          desc: el.描述
        }
      })
      // 调用接口批量新增商品
      addItems({
        items: _data
      }).then(res => {
        if (res.data.code === 200) {
          message.success('批量添加商品成功', 2, () => {
            getItems()
          })
        }
      })
    }
    return false
  }
  // 点击下载excel模板
  const downLoadTpl = () => {
    const data = [
      {
        商品名:'商品a',
        价格: 10,
        描述: '这里输入描述'
      }
    ]
    const ws = utils.json_to_sheet(data);
    const wb = utils.book_new();
    utils.book_append_sheet(wb, ws, "Data");
    writeFileXLSX(wb, "商品模板.xlsx");
  }

  // 删除商品
  const removeItem = (id: number) => {
    modal.confirm({
      title: '删除商品',
      content: '此操作会彻底删除该商品!!继续吗?',
      onOk: () => {
        delItem(id).then(res => {
          if (res.data.code === 200) {
            message.success(res.data.msg, 2, () => {
              getItems()
            })
          }
        })
      }

    })
  }
  return (
    <div className='itemLists'>
      <SearchBar onSearch={onSearch} />
      <div className="btns">
        <Upload
          action="#"
          beforeUpload={uploadXlsx}
          accept='.xls, .xlsx'>
          <Button type='primary'>批量新增商品</Button>
        </Upload>
        <Button type='primary' onClick={
          () => {
            navigate('/itemAdd')
          }
        }>新增商品</Button>
        <Button type='link' onClick={downLoadTpl}>下载模板</Button>

      </div>
      <Table
        rowKey={'id'}
        columns={columns}
        dataSource={items}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
          total,
          onChange: paginationChange
        }}
      />
      {contextHolder}
    </div>
  )
}
